package org.jeecg.modules.sistersophie.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.sistersophie.entity.StudentInfo;
import org.jeecg.modules.sistersophie.facade.StudentFacade;
import org.jeecg.modules.sistersophie.service.IStudentInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: t_student_info
 * @Author: jeecg-boot
 * @Date:   2021-05-23
 * @Version: V1.0
 */
@Api(tags="t_student_info")
@RestController
@RequestMapping("/sistersophie/studentInfo")
@Slf4j
public class StudentInfoController extends JeecgController<StudentInfo, IStudentInfoService> {
	@Autowired
	private IStudentInfoService studentInfoService;

	@Autowired
	private StudentFacade studentFacade;
	
	/**
	 * 分页列表查询
	 *
	 * @param studentInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "t_student_info-分页列表查询")
	@ApiOperation(value="t_student_info-分页列表查询", notes="t_student_info-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(StudentInfo studentInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		studentInfo.setIsDelete(0);
		QueryWrapper<StudentInfo> queryWrapper = QueryGenerator.initQueryWrapper(studentInfo, req.getParameterMap());
		Page<StudentInfo> page = new Page<StudentInfo>(pageNo, pageSize);
		IPage<StudentInfo> pageList = studentInfoService.page(page, queryWrapper);
		if(pageList != null && pageList.getRecords() != null && pageList.getRecords().size() > 0){
			for(StudentInfo info : pageList.getRecords()){
				if(StringUtils.isNotBlank(info.getPhone()) && info.getPhone().split("-").length > 1){
					info.setPhonePrefix(info.getPhone().split("-")[0]);
					info.setPhone(info.getPhone().split("-")[1]);
				}
				info.setStudentName(info.getFirstName() + " " + info.getLastName());
			}
		}
		return Result.OK(pageList);
	}

	 @ApiOperation(value="t_student_info-分页列表查询", notes="t_student_info-分页列表查询")
	 @GetMapping(value = "/course/list")
	 public Result<?> queryCoursePageList(StudentInfo studentInfo,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 Page<StudentInfo> page = new Page<StudentInfo>(pageNo, pageSize);
		 IPage<StudentInfo> pageList = studentInfoService.selectStudentInfoAndNotInCourse(page, studentInfo);
		 if(pageList != null && pageList.getRecords() != null){
			 for(StudentInfo info : pageList.getRecords()){
				 info.setStudentName(info.getFirstName() + " " + info.getLastName() + " " + info.getChineseName());
				 if(info.getCourseId() != null && info.getCourseId().intValue() > 0){
					 info.setIsEdit(1);//1=不可编辑 0=可编辑
				 }else{
				 	info.setIsEdit(0);
				 }
			 }
		 }
		 return Result.OK(pageList);
	 }
	
	/**
	 *   添加
	 *
	 * @param studentInfo
	 * @return
	 */
	@AutoLog(value = "t_student_info-添加")
	@ApiOperation(value="t_student_info-添加", notes="t_student_info-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody StudentInfo studentInfo) {
		studentFacade.save(studentInfo);
		return Result.OK("Added successfully！");
	}
	
	/**
	 *  编辑
	 *
	 * @param studentInfo
	 * @return
	 */
	@AutoLog(value = "t_student_info-编辑")
	@ApiOperation(value="t_student_info-编辑", notes="t_student_info-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody StudentInfo studentInfo) {
		studentFacade.edit(studentInfo);
		return Result.OK("Edit successfully!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "t_student_info-通过id删除")
	@ApiOperation(value="t_student_info-通过id删除", notes="t_student_info-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		studentFacade.deleteStudent(id);
		return Result.OK("Successfully deleted!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "t_student_info-批量删除")
	@ApiOperation(value="t_student_info-批量删除", notes="t_student_info-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.studentInfoService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("Batch delete successfully!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "t_student_info-通过id查询")
	@ApiOperation(value="t_student_info-通过id查询", notes="t_student_info-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		StudentInfo studentInfo = studentInfoService.getById(id);
		if(studentInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(studentInfo);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param studentInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StudentInfo studentInfo) {
        return super.exportXls(request, studentInfo, StudentInfo.class, "t_student_info");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return importStudentExcel(request, response);
    }
	 private Result<?> importStudentExcel(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(0);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<StudentInfo> list = ExcelImportUtil.importExcel(file.getInputStream(), StudentInfo.class, params);
				 if(list != null && list.size() > 0){
					 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
					 for(StudentInfo sinfo : list){
						 sinfo.setIsDelete(0);
						 sinfo.setCreateName(sysUser.getUsername());
						 sinfo.setUpdateName(sysUser.getUsername());
						 sinfo.setCreateTime(new Date());
						 sinfo.setUpdateTime(new Date());
					}
				 }
				 //update-begin-author:taoyan date:20190528 for:批量插入数据
				 long start = System.currentTimeMillis();
				 studentInfoService.saveBatch(list);
				 //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				 //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 //update-end-author:taoyan date:20190528 for:批量插入数据
				 return Result.ok("File imported successfully！data rows：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("File import failed:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }

}
